import React, { useState, useEffect, useRef, useCallback } from 'react'
import {
  postCompanyInfoDynamicPage,
  postCompanyInfoDynamicQueryCount,
  postCompanyInfoDynamicQueryCountSubType,
  postStdsParameterTreeList
} from '@/api/companyDetail/CompanyDynamic.ts'
import TabListCom from './components/TabList.tsx' // 假设已转换为React组件
import { DetailModal } from '@hs-server/components'
import { useDebounceFn } from 'ahooks'
import { Empty, Input, Pagination, Spin, Tag, Typography } from 'antd' // 假设已转换为React组件
import { initPageType, usePageChange } from '@hs-admin/utils'
import './dynamic.css'

interface ListType {
  eventSegment?: string
  eventTitle?: string
  eventType?: string
  occurDate?: string
  eventSubType?: string
  eventSubtitle?: string
}

interface TabType {
  label: string
  value: string
  num: number
  children?: TabType[]
}

interface Props {
  companyCode?: string
}

const { Paragraph } = Typography

const { Search } = Input

const initPage: initPageType = {
  current: 1,
  total: 0,
  pageSize: 10,
  morePageOptions: {
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => `共 ${total} 条数据`,
    pageSizeOptions: [10, 20, 30, 40]
  }
}

const CompanyDynamic: React.FC<Props> = ({ companyCode }) => {
  const [keyword, setKeyword] = useState('')
  const [tabList, setTabList] = useState<TabType[]>([])
  const [tabLabelList, setTabLabelList] = useState<TabType[]>([])
  const [activeTab, setActiveTab] = useState('')
  const [typeList, setTypeList] = useState<TabType[]>([])
  const [typeLabelList, setTypeLabelList] = useState<TabType[]>([])
  const [activeType, setActiveType] = useState('')
  const [listData, setListData] = useState<ListType[]>([])

  const [iscount, setiscount]: any = useState('')
  const DetailModalRef = useRef<any>(null)

  const changeTab = (item: TabType) => {
    setActiveTab(item.value)
    setActiveType('')
    setTypeLabelList([
      { label: '全部', value: '', num: 0 },
      ...(item.children?.map((second) => ({ ...second, label: second.name, value: second.name })) ?? [])
    ])
  }

  const changeType = (item: TabType) => {
    setActiveType(item.value)
  }

  const handleSearch = (value: string) => {
    setKeyword(value)
    setActiveTab('')
    setActiveType('')
  }

  const doRequest = useCallback(
    async (page: number, pageSize: number) => {
      const res = await postCompanyInfoDynamicPage({
        companyCode: companyCode,
        current: page,
        eventSubType: activeType,
        eventType: activeTab,
        keyword,
        pageSize
      })
      setListData(res.list || [])
      setiscount(res.total ?? '')
      return res.total || 0
    },
    [activeTab, activeType, companyCode, keyword]
  )

  const { pagination, resetPageAndTriggerRequest, loading } = usePageChange(initPage, doRequest)

  useEffect(() => {
    resetPageAndTriggerRequest()
  }, [resetPageAndTriggerRequest])

  useEffect(() => {
    postCompanyInfoDynamicQueryCount({
      companyCode: companyCode,
      keyword
    }).then((res) => {
      setTabList(
        res.map((item: { type: any; total: any }) => ({
          ...item,
          label: item.type,
          num: item.total || 0,
          value: item.type
        }))
      )
    })
  }, [companyCode, keyword, tabLabelList])

  useEffect(() => {
    if (!typeLabelList.length) return
    postCompanyInfoDynamicQueryCountSubType({
      companyCode: companyCode,
      eventType: activeTab,
      keyword: keyword
    }).then((res) => {
      setTypeList(
        res.map((item: { type: any; total: any }) => ({
          ...item,
          label: item.type,
          num: item.total || 0,
          value: item.type
        }))
      )
    })
  }, [activeTab, companyCode, keyword, typeLabelList])

  function handleDetail(item) {
    DetailModalRef.current?.showModal(item)
  }

  const inputSearch = useDebounceFn(
    (value) => {
      handleSearch(value)
    },
    { wait: 500 }
  )

  useEffect(() => {
    postStdsParameterTreeList({}).then((res) => {
      const allData = res.filter((item: any) => item.name == '事件类型')[0]
      setTabLabelList(allData.children.map((second) => ({ ...second, label: second.name, value: second.name })))

      let childrenList: any[] = []
      const childrenNameList = new Set()
      allData.children.forEach((item) => {
        item.children.forEach((second) => {
          childrenNameList.add(second.name)
        })
      })
      childrenList = [...childrenNameList].map((item) => ({
        label: item,
        value: item
      }))
      allData.children.forEach((item) => {
        item.children.forEach((second) => {
          const findItem: any = childrenList.find((ele) => ele.label === second.name)
          Object.keys(second).forEach((key) => {
            if (key !== 'label' && key !== 'value') {
              findItem[key] = second[key]
            }
          })
        })
      })
      setTabLabelList((prevState) => [
        {
          label: '全部',
          value: '',
          num: 0,
          children: [...childrenList]
        },
        ...prevState
      ])
      changeTab({
        label: '全部',
        value: '',
        num: 0,
        children: [...childrenList]
      })
    })
  }, [])

  return (
    <div className="company-dynamic-wrapper" id="企业动态" data-count={iscount}>
      <div className="company-dynamic-content">
        <div className="com-box special-box">
          <div className="com-title">动态列表</div>
          <span className="tab-item">搜索：</span>
          <Search
            allowClear
            className="search-box"
            style={{ width: '226px' }}
            placeholder="关键词搜索"
            onSearch={(value) => handleSearch(value)}
            onChange={(e) => {
              inputSearch.run(e.target.value)
            }}
          />
          <TabListCom title="动态类型" list={tabList} activeTab={activeTab} onChangeTab={changeTab} />
          <TabListCom title="二级分类" list={typeList} activeTab={activeType} onChangeTab={changeType} />
        </div>
        <Spin spinning={loading}>
          <div className="com-box">
            {listData.map((item: any, index) => (
              <div key={index} className="list-item-wrapper" onClick={() => handleDetail(item)}>
                <div className="item-title">
                  <Paragraph
                    ellipsis={{
                      rows: 1,
                      tooltip: true
                    }}>
                    <span className="hover:text-#0779ff text-18px">{`${item.eventSegment}: ${item.eventTitle}`}</span>
                  </Paragraph>
                  <span>{item.eventSubType}</span>
                  <div>
                    <Tag className="ml-10px" color={item.eventQuality === '利好' ? 'green' : 'red'}>
                      {item.eventQuality === '利好' ? '利好' : '预警'}
                    </Tag>
                  </div>
                </div>
                <div className="list-item-content">
                  <div className="data-item">
                    <span className="item-label">发生日期：</span>
                    <span className="item-value">{item.occurDate}</span>
                  </div>
                  <div className="data-item">
                    <span className="item-value">{item.eventSubtitle}</span>
                  </div>
                </div>
              </div>
            ))}
            {!listData.length && <Empty description="无数据" />}
            {pagination.total > 0 && (
              <div className="flex justify-end pt-25px pb-15px">
                <Pagination {...pagination} />
              </div>
            )}
          </div>
        </Spin>
      </div>
      <DetailModal ref={DetailModalRef} />
    </div>
  )
}

export default CompanyDynamic
